$import("biz.base.StoreHelper,biz.base.FormEditorUtil,biz.base.RenderUtil,biz.base.GridEditorUtil"); 

function CompositePanel(conf){
	var me=this;
	this.addRecordUrl="./../meta/addRecord";
	  this.updateRecordUrl="./../meta/updateRecord";
	  this.loadDataUrl="./../meta/query";
	if( typeof(conf)== 'string'){
		this.metaCode=conf;
	}else if( typeof(conf)== 'object'){
		this.initialConfig=conf;
		Ext.apply(me,conf);
	}
  this.name		  = null;
  this.title	  = null;
  
  this.dataStore  = null;
  this.formPanel  = null;
  this.gridPanel  = null;
  this.initialized= false;
  this.markRefresh= false;
  
  this.handlers	  = this.mapButtons();
  this.attrConfig = this.defaultAttrConfig();
  Ext.apply(this,this.attrConfig);
  if(this.searchFields&&this.searchFields.length>0){
	  this.searchFormConfig = this.defaultSearchFormConfig('north');
  }
  this.pageConfig = this.defaultPageConfig(20);
  this.dataConfig = this.defaultDataConfig();
  var bs=this.dataConfig.baseParams =this.dataConfig.baseParams || {'id':this.getMetaId(),"pageInfo.start":0,"pageInfo.limit":20};
  if(this.defaultFilters){
	  for(var k in this.defaultFilters){
		  bs['filter.'+k]=this.defaultFilters[k];
	  }
  }
  this.dataConfig.proxy=new Ext.data.RestProxy({
	  url:me.loadDataUrl
  });
  this.gridConfig = this.defaultGridConfig('west');
  
  this.colsConfig = null;
 
};

CompositePanel.prototype.getMetaId = function(){
	return this.metaData.id;
} ;

CompositePanel.prototype.getText = function(){
	return this.metaData.text;
} ;

//map存按钮配置
CompositePanel.prototype.mapButtons=function() {
	var map = new HashMap();
		map.put('-','-');
		map.put('splitter','-');
		map.put('doCloned', {text:'复制',iconCls:'icon-copied', tooltip:{text:'复制当前选中的项'}} );
		map.put('doCopied', {text:'复制',iconCls:'icon-copied', tooltip:{text:'复制当前选中的项'}} );
		map.put('doAddNew', {text:'新建',iconCls:'icon-create', tooltip:{text:'在新页面创建记录'}} );
		map.put('doCreate', {text:'新建',iconCls:'icon-create', tooltip:{text:'创建一个新的记录'}} );
		map.put('doInsert', {text:'插入',iconCls:'icon-create', tooltip:{text:'创建新的插入记录'}} );
		map.put('doUpdate', {text:'更新',iconCls:'icon-update', tooltip:{text:'提交当前修改内容'}} );
		map.put('doDelete', {text:'删除',iconCls:'icon-delete', tooltip:{text:'删除当前选中的项'}} );
		map.put('doCommit', {text:'提交',iconCls:'icon-submit', tooltip:{text:'提交所有修改内容',title:'全部提交到服务器'}} );
		map.put('doModify', {text:'编辑',iconCls:'icon-modify', tooltip:{text:'修改当前选中的项'}} );
		map.put('doDetail', {text:'详细',iconCls:'icon-detail', tooltip:{text:'查看选中详细信息'}} );
		map.put('doSearch', {text:'查询',iconCls:'icon-search', tooltip:{text:'根据条件重新查询'}} );
		map.put('doReload', {text:'刷新',iconCls:'icon-reload', tooltip:{text:'刷新当前页面数据'}} );
		map.put('doFinish', {text:'完成',iconCls:'icon-finish', tooltip:{text:'标记当前项目完成',title:'即时运行'}} );
		map.put('doSubmit', {text:'提交',iconCls:'icon-submit', tooltip:{text:'提交当前表单内容',title:'提交表单到服务器'}} );
		map.put('doCancel', {text:'取消',iconCls:'icon-reset',  tooltip:{text:'取消当前修改状态'}} );
		map.put('doReset',  {text:'重置',iconCls:'icon-reset',  tooltip:{text:'重置输入为原始状态'}} );
		map.put('doExecute',{text:'运行',iconCls:'icon-execute',tooltip:{text:'执行选中的查询',title:'选中查询结果'}} );
		map.put('showProperty',{text:'属性',iconCls:'icon-finish'} );
		map.put('doIn',{text:'导入',iconCls:'icon-reload'} );
		map.put('doOut',{text:'导出',iconCls:'icon-reload'} );
	return map;
};

//获取按钮配置
CompositePanel.prototype.getButtons = function(names){
	var arr = [];
	for(var i=0;i<names.length;i++){
		arr[i] = this.getButton(names[i]);
	}
	return arr;
};

CompositePanel.prototype.getButton = function(name){
	var btn  = this.handlers.get(name);
	if(!btn){btn={text:name,iconCls:'icon-reset'};}
	if( btn.text ){
		btn.xtype="button";
		btn.itemId=name;
		btn.handler=fnBind(this.btnAction,this);
	}
	return btn;
};

//面板初始方法
CompositePanel.prototype.init = function(){
  this.initBefore();
  this.initStore(); 
  this.initPanel(); 
  this.initFinish();
};



CompositePanel.prototype.initBefore = function(){};

CompositePanel.prototype.initStore  = function(){
	if( this.dataConfig ){
		if(!this.dataConfig.fields){
			this.dataConfig.fields=this.getColsConfig().names;
		}
		if(this.dataConfig.idProperty && !this.dataConfig.sortInfo){
			this.dataConfig.sortInfo={field:this.dataConfig.idProperty,direction: 'DESC'};
		}
		this.dataStore =  new Ext.data.JsonStore(this.dataConfig);
	}
};

CompositePanel.prototype.initPanel = function(){
	 if( this.gridConfig ){
		 if(!this.gridConfig.columns){
		     this.gridConfig.columns=this.getColsConfig().items;
		 }
		 if( this.gridConfig.actions){
			 var acts = this.gridConfig.actions;
			 for(var i=0;i<acts.length;i++){
				 this.gridConfig.columns.push(acts[i]);
			 }
		 }
		 if(!this.gridConfig.colModel){
			 this.gridConfig.colModel = this.createColModel(this.getColsConfig().model);
		 }
		 if(this.gridConfig.filter && this.gridConfig.plugins.length<1){
	  	  }
		 
		 this.gridConfig.store=this.dataStore;
		var pbar = this.pageConfig;
		if( pbar && !this.gridConfig.bbar ){
			pbar.store=this.dataStore;
			var plimit=pbar.store.baseParams['pageInfo.limit'];
			if( plimit ){ 
				pbar.pageSize=plimit; 
			}
			if( pbar.combo ){
				pbar.combo.setValue(pbar.pageSize);
			}
			if( pbar.exportUrl ){
				pbar.items[pbar.items.length]=this.getButtons(["doExport"])[0];
			}
			this.gridConfig.bbar = Ext.create(pbar); 
		 }
		var listeners=this.gridConfig.listeners=this.gridConfig.listeners||{};
		listeners["rowdblclick"]=this.doubleClick;
		listeners["rowclick"]=this.singleClick;
	 }
	 var items=[];
	 if(this.searchFormConfig){
		 items.push(this.searchFormConfig);
	 }
	 if(this.detailFormConfig){
		 this.detailFormConfig["region"]='center';
		 this.gridConfig["region"]='west';
		 items.push(this.detailFormConfig);
	 }else{
		 this.gridConfig["region"]='center';
	 }
	 items.push(this.gridConfig);
	 new Ext.Viewport({
		layout:'border',
		items:items
	 });
	 this.gridPanel=Ext.getCmp(this.gridConfig.id);
	 if(this.searchFormConfig){
		 this.searchFormPanel=Ext.getCmp(this.searchFormConfig.id);
	 }
	
};

CompositePanel.prototype.initFinish = function(){};

//页面刷新
CompositePanel.prototype.display = function(){
    if(!this.initialized){
      this.initialized = true;
      this.init();
    }else{
      this.refresh();
    }
};

CompositePanel.prototype.selectFirstRow=function(){
	var selModel = this.gridPanel.getSelectionModel();
	if(typeof(selModel.selectFirstRow)=='function'){
		selModel.selectFirstRow();
	}
};


CompositePanel.prototype.refresh = function(params){
	var store = this.dataStore;
	if(params){
		store.reload({params:params});
	}else{
		store.reload();
	}
};

CompositePanel.prototype.singleClick = function(grid, rowindex, e){  
	
};
//双击事件 
CompositePanel.prototype.doubleClick= function(grid, rowindex, e){	 
	   if(this['doModify'])this['doModify']();
};
//单击事件
CompositePanel.prototype.checkSingle=function(){
	var count = this.gridPanel.selModel.getCount();
	if(count<1){
		Ext.Msg.alert("提示", "没有选择记录，请只选择需要操作的行。");
	}else if(count>1){
		Ext.Msg.alert("提示", "选择了多行，请只选择需要操作的行。");
	}else{
		return true;
	}
	return false;
};
//单选记录
CompositePanel.prototype.checkSelect=function(){
	var count = this.gridPanel.selModel.getCount();
	if(count>0){return true;}
	Ext.Msg.alert("提示", "没有选择记录，请只选择需要操作的行。");
	return false;	
};


/**below is for event handler***/
CompositePanel.prototype.btnAction=function(btn,evt){
		var bFunc = this[btn.itemId+"Before"];
		if((typeof(bFunc)=='function'&&bFunc.apply(this,[btn,evt]))||!bFunc){
			var ret = false;
			if(typeof(this[btn.itemId])=='function' ){
				ret = this[btn.itemId].apply(this,[btn,evt]);
			}
			var aFunc = this[btn.itemId+"Finish"];
			if( typeof(aFunc)=='function' ){
				aFunc.apply(this,[btn,evt,ret]);
			}
		}
};

CompositePanel.prototype.showAddNew=function(){
	var me=this,name='addNewWin'+this.getMetaId();
	var xname="addNewForm"+this.getMetaId();
	var win=Ext.getCmp(name),form =Ext.getCmp(xname);
	if(!win) {
		var flds=this.loadFormFields();
		form = new Ext.FormPanel({
			
		        frame: true,
		        labelAlign: 'right',
		        labelWidth: 85,
		        id:xname,
		        jsonSubmit:true,
		        autoScroll:true,
		        closable:true,
		        waitMsgTarget: true,
		        items: flds,
		        buttons:[{
	             text:'确认',
	             handler:function(){
	             	var url=me.addRecordUrl;
	             	var conf={
	 	  	   	  		    clientValidation: true,
	 	  	   	  		    url: url,
	 	  	   	  		    waitMsg:"保存中，请稍后...",
	 	  	   	  		    success: function(form, action) {
	 	  	   		  		  	me.dataStore.reload();
	 	  	   		  		  	var win=Ext.getCmp(name);
	 	  	   		  		  	win.destroy();
	 	  	   	     		},
	 	  	   	  		    failure: function(form, action) {
	 	  	   	  		    	me.dataStore.reload();
	 	  	   	  		    	var win=Ext.getCmp(name);
	 	  	   	  		    	win.destroy();
	 	  	   	  		 		return Ext.Msg.alert("结果","新建失败");
	 	  	   	  		    	
	 	  	   	  		    }
	 	  	   	  		};
	 	  	    	form.getForm().submit(conf);
	             }
	         },{
	             text: '取消',
	             handler: function(){
	             	var win=Ext.getCmp(name);
	             	win.close();
	             }
	         }]
		 });
		
		
		 win = new Ext.Window({
	         layout:'fit',
	         id:name,
	         scrollable:true,
	         modal:true,
	         closeAction: 'close',
	         title:'新建',
	         width:500,
	         height:280,
	         plain: true,
	         items: form
	         
	     });
	}
	 var sidField=form.getForm().findField(this.dataConfig.idProperty);
	 if(sidField){
		 sidField.setValue(-1);
		 sidField.setVisible(false);
	 }
	 var tpl=this.defaultRecType;
	 if(tpl){
		 for(var key in tpl){
			var f= form.getForm().findField("map."+key);
			if(f){
				f.setValue(tpl[key]);
			}
		 }
	 }
	 var f=form.getForm().findField('map.seq');
	 if(f){
		 var total=this.dataStore.getTotalCount( );
		 f.setValue(total+1);
		 f.setVisible(false);
	 }
	 return  win.show();
}
CompositePanel.prototype.doAddNew=function(){
    if(this.attrConfig.readOnly==true){
    	return;
    }
    this.showAddNew();
};


CompositePanel.prototype.doCreate=function(){
	var RecordFunc = this.dataStore.recordType,tpl=this.defaultRecType,
	newRec = new RecordFunc(tpl,-1),
	idx = this.dataStore.getCount();
    if( this.gridPanel.isXType('editorgrid') ){
     	this.gridPanel.stopEditing();
 	    this.dataStore.insert(idx,newRec);
    	this.gridPanel.startEditing(idx, 0);
    }else{
 	    this.dataStore.insert(idx,newRec);
    }
	return newRec;
};

CompositePanel.prototype.doCopied=function(){
	if(this.checkSingle()){
		var rec = this.gridPanel.selModel.getSelected();
		var idx = rec.store.indexOf(rec);
     	var idFld = this.dataConfig.idProperty;
    	var id = rec.get(idFld)? (-Math.abs(rec.get(idFld))):0;
     	var newRec = rec.copy(id);
     		newRec.modified=newRec.data;
          	newRec.set(idFld,id);
          	newRec.phantom=true;
 	    if( this.gridPanel.isXType('editorgrid') ){
	     	this.gridPanel.stopEditing();
	 	    this.dataStore.insert(idx,newRec);
	    	this.gridPanel.startEditing(idx, 0);
	    }else{
	 	    this.dataStore.insert(idx,newRec);
	    }
	}
};

CompositePanel.prototype.doInsert=function(){
	var idx = 0;
	var sCount = this.gridPanel.selModel.getCount();
	if( sCount>0 ){
		var rec = this.gridPanel.selModel.getSelected();
		idx = rec.store.indexOf(rec);
	}
	var RecordFunc = this.dataStore.recordType,tpl=this.defaultRecType,
	newRec = new RecordFunc(tpl,-1);
    if( this.gridPanel.isXType('editorgrid') ){
     	this.gridPanel.stopEditing();
 	    this.dataStore.insert(idx,newRec);
    	this.gridPanel.startEditing(idx, 0);
    }else{
 	    this.dataStore.insert(idx,newRec);
    }
	return newRec;
};

CompositePanel.prototype.doModifyBefore=function(){
	return this.checkSingle();
};
CompositePanel.prototype.doExecuteBefore=function(){
	return this.checkSingle();
};

CompositePanel.prototype.doModify=function(){
	var rec = this.gridPanel.selModel.getSelected();
    var sid = rec.get(this.dataConfig.idProperty);
    if(this.attrConfig.readOnly==true){
    	return;
    }
    this.showModifyWin(rec);
};

CompositePanel.prototype.showModifyWin=function(record){
	var me=this,name='modifyWin'+this.getMetaId(),
	formName="modifyForm"+this.getMetaId();
	var win=Ext.getCmp(name);
	if(!win) {
		var flds=this.loadFormFields();
		 var form = new Ext.FormPanel({
		        frame: true,
		        labelAlign: 'right',
		        id:formName,
		        jsonSubmit:true,
		        labelWidth: 100,
		        width:220,
		        closable:true,
		        autoScroll:true,
		        waitMsgTarget: true,
		        items: flds,
		        buttons:[{
	             text:'确认',
	             handler:function(){
	            	 var sid=form.getForm().findField("id").getValue()*1,
	            	 url="../meta/updateRecord";
	             	var conf={
	 	  	   	  		    clientValidation: true,
	 	  	   	  		    url: url,
	 	  	   	  		    waitMsg:"保存中，请稍后...",
	 	  	   	  		    success: function(form, action) {
	 	  	   		  		  	me.dataStore.reload();
	 	  	   		  		  	var win=Ext.getCmp(name);
	 	  	   		  	win.destroy();
	 	  	   	     		},
	 	  	   	  		    failure: function(form, action) {
	 	  	   	  		    	me.dataStore.reload();
	 	  	   	  		    	var win=Ext.getCmp(name);
	 	  	   	  		win.destroy();
	 	  	   	  		 		return Ext.Msg.alert("结果","更新失败");
	 	  	   	  		    	
	 	  	   	  		    }
	 	  	   	  		};
	 	  	    	form.getForm().submit(conf);
	             }
	         },{
	             text: '取消',
	             handler: function(){
	             	var win=Ext.getCmp(name);
	             	win.destroy();
	             }
	         }]
		 });
		 
		 var win = new Ext.Window({
	         layout:'fit',
	         id:name,
	         modal:true,
	         closeAction: 'close',
	         title:'编辑',
	         width:500,
	         height:300,
	         plain: true,
	         items: form
	     });
		 win.loadRecord=function(record){
			 Ext.each(form.items.items,function(f,i){
				 var name=f["name"],index=name.indexOf('.');
				 if(index>-1){
					 name=name.substring(index+1);
					 f.setValue(record.get(name));
				 }
			 });
			 var sid=record.get(me.dataConfig.idProperty);
			 form.getForm().findField('id').setValue(sid);
			 form.getForm().findField('metaId').setValue(me.getMetaId());
		 };
	}
	
	 win.loadRecord(record);
	 return  win.show();
};

CompositePanel.prototype.doDetail=function(){
	var rec = this.gridPanel.selModel.getSelected();
    var sid = rec.get(this.dataConfig.idProperty);
    if(this.attrConfig.readOnly==true){
    	return;
    }
 
};


CompositePanel.prototype.doDeleteBefore=function(){
	if( this.checkSelect() ){
		var self=this;
		function callback(btn){
			if( btn=='yes' ){
				self.doDelete();
			}
		}
		Ext.Msg.confirm('请确认!','确定要删除选中的记录？',callback);
	}
	return false;
};
CompositePanel.prototype.doDelete=function(){
	var arr = this.gridPanel.selModel.getSelections();
	if(arr.length==0)return;
	var ids="";
	for(var i=0;i<arr.length;i++){
		var row=arr[i];
		if(i>0){
			ids+=",";
		}
		ids+=row.get(this.dataConfig.idProperty);
	}
	var url="../meta/deleteBySids?metaId="+this.getMetaId()+"&ids="+ids;
	doHttpPost(url);
	this.doReload();
};

CompositePanel.prototype.doReload=function(){
	this.refresh();
};

CompositePanel.prototype.doFinish=function(){
};

//重置
CompositePanel.prototype.doReset=function(){
	var flds = this.getFieldValues();
	for(var name in flds){
		this.dataStore.setBaseParam('filter.'+name,'');
	}
	this.searchFormPanel.getForm().reset();
	this.dataStore.reload();
};

//面板赋值
CompositePanel.prototype.setPropertyData=function(){
    var rec = this.gridPanel.selModel.getSelected();
 	var data= this.getPropertyConfig(rec);     	 
	window.parent.setProperty(data);
};

CompositePanel.prototype.showAndCloseProperty=function(){};
//查询
CompositePanel.prototype.doSearch=function(){
	var flds = this.getFieldValues();
	for(var name in flds){
		this.dataStore.setBaseParam("filter."+name,flds[name]);
	}	
	this.refresh({params:{}});
};

CompositePanel.prototype.getFieldByMeta=function(field){
	var attr={},attrs = field["attrs"];
	if(attrs.required){attr.allowBlank=true;}
	Ext.applyIf(attr,field);
	delete attr["attrs"];
	var fld= FormEditorUtil.get(field['type'],attr);
	if( fld.fieldLabel && fld.allowBlank===false ){
		fld.fieldLabel += '<font color=red>*</font>';
	}
	return fld;
};
CompositePanel.prototype.loadFormFields=function(){
	var colsConfig=this.getColsConfig(),flds=[],datum=colsConfig.datum,
	df=this.defaultRecType;
	for(var i=0;i<datum.length;i++){
		var fld = this.getFieldByMeta(datum[i]),name=fld["name"];
		if(df&&df.hasOwnProperty(name)){
			fld["value"]=df[name];
			fld["hidden"]=true;
		}
		fld["name"]="map."+fld["name"];
		flds.push(fld);
	}
	flds.push({
		name:"id",
		xtype:'numberfield',
		hidden:true
	});
	flds.push({
		name:"metaId",
		value:this.getMetaId(),
		xtype:'numberfield',
		hidden:true
	});
	return flds;
};


CompositePanel.prototype.doSubmit=function(){
	  var me=this,conf={
  		    clientValidation: true,
  		    url: this.updateRecordUrl,
  		    success: function(form, action) {
  		      me.dataStore.reload();
     		},
  		    failure: function(form, action) {
  		        switch (action.failureType) {
  		            case Ext.form.Action.CLIENT_INVALID:
  		                Ext.Msg.alert('失败', '表单验证失败。');
  		                break;
  		            case Ext.form.Action.CONNECT_FAILURE:
  		                Ext.Msg.alert('失败', '异步提交失败。');
  		                break;
  		            case Ext.form.Action.SERVER_INVALID:
  		               Ext.Msg.alert('失败', action.result.msg);
  		       }
  		    }
  		};
   	  this.formPanel.getForm().submit(conf);
};

CompositePanel.prototype.loadFormValue=function(store,recs,opts){
	if(recs.length==0){
		alert("记录不存在");
		return;
	}
	var form = this.formPanel.getForm();
	var cols = this.getColsConfig().items;

	for(var i=0;i<cols.length;i++){
		var fldName = cols[i];
		var fld = form.findField('map.'+fldName);
		if(fld){
			fld.setValue(recs[0].get(fldName));
		}
	}
};


CompositePanel.prototype.getFieldValues = function(dirtyOnly){
    var o = {},  n, key, val;
    var loopField=function(f) {
         if (!f.disabled && (dirtyOnly !== true || f.isDirty())) {
        	if (f.isComposite) {
                f.items.each(loopField);
            } else if (f instanceof Ext.form.CheckboxGroup && f.rendered) {
                f.eachItem(loopField);
            }else{
 	            n = f.getName();
 	            if(n){
 	            	key = o[n];
 		            val = f.getValue();
 		           if(Ext.isDefined(key)){
 		                if(Ext.isArray(key)){
 		                    o[n].push(val);
 		                }else{
 		                    o[n] = [key, val];
 		                }
 		            }else{
 		                o[n] = val;
 		            }
 	            }
	            
            }
        }
    };
    
   // this.items.each(loopField);
    this.searchFormPanel.getForm().items.each(loopField);
    return o;
};

CompositePanel.prototype.doCancel=function(){
	this.doReload();
};

CompositePanel.prototype.doCommit=function(){
	var modifiedRecords = this.dataStore.getModifiedRecords();
    var hasChanged = (modifiedRecords.length>0);
    var hasError = false;
    for(var i=modifiedRecords.length;i>0;i--){
		var rec=modifiedRecords[i-1];
 		var chg=rec.getChanges();
		var sid = rec.get(this.dataConfig.idProperty);
 		var url=(rec.phantom?this.addRecordUrl:this.updateRecordUrl);
 		var params={metaId:this.getMetaId(),id:(sid>0?sid:0),map:chg};
		var me=this;
		 Ext.Ajax.request({jsonSubmit:true,url:url,params:params,success:function(response){
			 rec.commit();
			if(i<=1){
				 var data=Ext.decode(response.responseText);
				 me.doReload();
			 }
			 
		 },failure:function(response){
			 error+=Ext.decode(response.responseText)["msg"];
			 rec.commit();
			 if(i<=1){
				 me.doReload();
			 }
		 }});
		 
 	}
};

CompositePanel.prototype.doUpdate=function(){
	var modifiedRecords = this.dataStore.getModifiedRecords();
	if(modifiedRecords.length==0)return Ext.Msg.alert('没有修改');
    var params={metaId:this.getMetaId(),id:sid,map:{}},data=params["map"];
    
    for(var i=modifiedRecords.length;i>0;i--){
		var rec=modifiedRecords[i-1];
 		var obj=rec.getChanges();
 		var flds=this.dataConfig.fields;//commit all?.....
 		var url=this.updateRecordUrl;
 		for(var f=0;f<flds.length;f++){
 			var fname = flds[f].name||flds[f];
 			var v=obj[fname]||rec.get(fname);
 			data[fname]=v;
 		}
	   
 	}
};



//获得表头配置
CompositePanel.prototype.getCompositeFields=function(label){
	var conf={ xtype:'compositefield',isComposite:true,isFormField:true,defaults:{xtype: 'textfield'},items:[]};
	if(label){
		conf.fieldLabel=label;
	}else{
		conf.hideLabel=true;
	}
	return conf.items;
};



//get table config from store and construts the data to girdplane data columnModel
CompositePanel.prototype.getColsConfig=function(){
	if( this.colsConfig ){
		 return this.colsConfig;
	}
	var fm=this.fm={},defaultRecType=this.defaultRecType={},colsConfig={ fieldMap:{},names:[], items:[], model:[], filter:[], datum:[] },
	fields=this.metaData["fields"],showColumns=this.showColumns||[],fieldMap=colsConfig.fieldMap;
	if(this.defaultFilters){
		Ext.apply(defaultRecType,this.defaultFilters);
	}
	for ( var k = 0; k < fields.length; k++) {
		var field = fields[k],name=field["name"];
		fm[name]=field;
		var attrs=field["attrs"]||{};
		if(attrs["defaultValue"]){
			defaultRecType[name]=attrs["defaultValue"];
		}
		attrs["hidden"]=!(showColumns.indexOf(field["name"])>-1);
		var colInfo = this.getColumnInfo(field);
		if(this.attrConfig.idProperty==name){
			Ext.applyIf(colInfo,{editable:false,allowBlank:false});
		}
		fieldMap[name]=colInfo;
		colsConfig.names.push(colInfo);
		colsConfig.items.push(colInfo);
		colsConfig.filter.push(this.getFiltersConfigByType( field));
		colsConfig.model.push(this.getFiltersColumnsConfigByType( field));
		colsConfig.datum.push(field);
	}
	 this.colsConfig=colsConfig;
	 return this.colsConfig;
};


CompositePanel.prototype.getColumnInfo=function(field){
	var columnInfo = {header:field["text"],name:field["name"],dataIndex:field["name"]};
	var dataType =field["type"],attr=field["attrs"];
	Ext.applyIf(columnInfo,attr);
	Ext.applyIf(columnInfo,{sortable:true});
	if(attr.required){columnInfo.allowBlank=false;}
	if(attr.readOnly){columnInfo.editable=false;}
	var enums=attr["enums"];
	if(enums&&typeof(enums)=="string"){
		enums=enums.substring(enums.indexOf('$')+1);
		enumData=metaData["refEnumMap"][enums];
		if(!enumData["map"]){
			var enumMap=enumData["map"]=enumData["map"]||{},vf=attr["valueField"]||"code",df=attr["displayField"]||"text";
			Ext.each(enumData.list,function(n,i){
				enumMap[n[vf]]=n[df];
			});
		}
		attr["enums"]=enumData;
	}
	columnInfo.renderer = RenderUtil.get(dataType,attr);
	
	columnInfo.editor = GridEditorUtil.get(dataType,attr);
	return columnInfo;
};

//gird title's filter config  by data type 
CompositePanel.prototype.getFiltersConfigByType=function(field){	
	var dataType = field["type"], colName = field["name"],attr=field["attrs"];
	var filtersConfig = {dataIndex:colName};
	Ext.applyIf(filtersConfig,attr);
	if(attr.enums){
		filtersConfig.type='list';
		filtersConfig.options=storeChangeToArray(attr.enums,attr["valueField"]||"code",attr["displayField"]||"text");
	}else switch(dataType){
		case 1:
			filtersConfig.type='string';
			break;
		case 2:
		case 3:
		case 6:
		case 7:
		case 8:
			filtersConfig.type='float';
			break;
		case -7:
		case -6:
		case -5:
		case 0:
		case 4:
		case 5:
			filtersConfig.type='int';
			break;
		case 91:
		case 92:
		case 93:
			filtersConfig.type='date';
			break;
		default:
			//columnInfo.type='auto';
	}

	return filtersConfig;
};


//gird title's filter  config  by data type 
CompositePanel.prototype.getFiltersColumnsConfigByType=function(field){
	var dataType = field["type"],colName = field["name"],alias = field["text"],ccItems = {dataIndex:colName,header:alias};
	if (dataType == 1 ) {
		ccItems.filterable=true;
	}else if(dataType == 0){
		ccItems.filter={};
	}else if (dataType == 91) {
		ccItems.filter={};
		ccItems.renderer=RenderUtil.onlyDate;
	}
	return ccItems;
};


//转化成数组格式
function storeChangeToArray(enumData,vf,df){
	var sa = [];
	var config = {},list=enumData.list;
	if (enumData == null) {
		return sa;
	}
	Ext.each(list,function(n,i){
		config = {
				id : n[vf],
				text : n[df]
			};
			sa.push(config);
	});
	return sa;
};

CompositePanel.prototype.getPropertyConfig=function(rec){
	var propertyConfig = {},fields=this.metaData["fields"];
	for ( var k = 0; k < fields.length; k++) {
		var f = fields[k],value = rec.get(f["name"]),type=f["type"],text=f["text"];
		if (type == 91) {
			value = RenderUtil.onlyDate(value);
		}else if (type== 92) {
			value = RenderUtil.onlyTime(value);
		}else if (type == 93) {
			value = RenderUtil.dateTime(value);
		}
		propertyConfig[text] = value == null ? ' ': value;
	}
	return propertyConfig;
};

CompositePanel.prototype.getfilters=function(data){
	var filters = new Ext.ux.grid.GridFilters({   	      
	        encode: false,
	        local: false,  
	        filters: data 
	    }); 
	return  filters;
};
/**
 * ext column create helper
 * @param data
 * @returns {Ext.grid.ColumnModel}
 */
CompositePanel.prototype.createColModel=function(data){
    return new Ext.grid.ColumnModel({
        columns: data.slice( 0, data.length),
        defaults: {
            sortable: true
        }
    });	
};
/**
 * set group field header
 * @param row
 * @param col
 * @param fld
 */
CompositePanel.prototype.setField=function(row,col,fld){
	this.formConfig.items[0].items[col-1].items[row-1]=fld;
};


//获取node配置
CompositePanel.prototype.getMetaData=function(){
	if(!this.metaData){
		this.loadMeta(this.metaCode);
	}
	return this.metaData;
};
CompositePanel.prototype.loadMeta=function(name){
	var url="../meta/getMetaByName?name="+name;
	var data=Ext.decode(doHttpPost(url).text);
	if(data["success"]){
		this.metaData=data["data"];
	}else{
		alert('未配置元数据')
	}
};
//默认attr配置
CompositePanel.prototype.defaultAttrConfig=function(){
	var attr={},metaData=this.getMetaData();
	Ext.applyIf(attr,metaData["attrs"]);
	Ext.applyIf(attr,{idProperty:'SID'});
    return attr;

};

CompositePanel.prototype.initDetailForm=function(region){
	var gridForm=Ext.getCmp(this.gridConfig.id),
	detailId=this.detailFormId="detail_"+this.getMetaId();
	var form=new Ext.form.FormPanel({
	  	  frame : true,
	  	  split:true,
	  	  region:region,
	  	  id:detailId,
	  	  layout:'form',
	  	  buttonAlign:'left',
	  	  buttons:[
	  	       {
	  	    	   text:'提交',
	  	    	   handler:function(){
	  	    		   var cur_row=gridForm["cur_row"];
	  	    		 if(!form.getForm().isDirty()&&!cur_row.phantom)return Ext.Msg.alert('提示','没有修改，无需提交');
	  	    		var sid=cur_row.get("SID")?cur_row.get("SID"):0;
	  	    		var urlBase = getContextBase()+"module/";
	  	    		var url=urlBase+(cur_row.phantom?"Mace-createRole.action":"Record-updateJSON.action");
	   	 			url=url+"?nid="+companel.getMetaId()+"&sid="+sid;
	  	    		   
	  	    		 var conf={
	  	   	  		    clientValidation: true,
	  	   	  		    url: url,
	  	   	  		    waitMsg:"保存中，请稍后...",
	  	   	  		    success: function(form, action) {
	  	   		  		  	var cols = companel.dataConfig.fields;
	  	   		  			for(var i=0;i<cols.length;i++){
	  	   		  				var fname = cols[i].name||cols[i];
	  	   		  				var fld = form.findField('dataTO.map.'+fname);
	  	   		  				if( fld ){
	  	   		  					fld.originalValue=fld.getValue();
	  	   		  				}
	  	   		  				var cbo = form.findField('combo.'+fname);
	  	   		  				if( cbo ){
	  	   		  					cbo.originalValue=cbo.getValue();
	  	   		  				}
	  	   		  			}
	  	   		  		cur_row.commit();
	  	   		  			companel.refresh();
	  	   	     		},
	  	   	  		    failure: function(form, action) {
	  	   	  		        switch (action.failureType) {
	  	   	  		            case Ext.form.Action.CLIENT_INVALID:
	  	   	  		                Ext.Msg.alert('失败', '表单验证失败。');
	  	   	  		                break;
	  	   	  		            case Ext.form.Action.CONNECT_FAILURE:
	  	   	  		                Ext.Msg.alert('失败', '异步提交失败。');
	  	   	  		                break;
	  	   	  		            case Ext.form.Action.SERVER_INVALID:
	  	   	  		               Ext.Msg.alert('失败', action.result.msg);
	  	   	  		       }
	  	   	  		    }
	  	   	  		};
	  	    		form.getForm().submit(conf);
	  	    	   }
	  	       }
	  	  ],
	  	  items:this.loadFormFields()
	    });
	return form;
};

//默认查询过滤表单
CompositePanel.prototype.defaultSearchFormConfig=function(region){
	var conf={xtype:'form',id:"searchForm"+this.getMetaId()},
	nameFieldMap=this.getColsConfig()["fieldMap"],fm=this.fm,
	searchFields=this.searchFields;
    conf.labelWidth= 75; 
    conf.height= 80; 
    conf.region=region;
    conf.split=true;
    conf.title='查询条件';
    conf.collapsible=true;
    conf.frame=true;
    conf.autoWidth=true;
    conf.buttons=[];
    var cfs={ xtype:'compositefield',isComposite:true,isFormField:true,defaults:{xtype: 'textfield'},items:[]},
    flds=cfs["items"];
    Ext.each(searchFields,function(name,i){
    	var fctrl=nameFieldMap[name],f=fm[name];
    	flds.push({xtype: 'displayfield',value:fctrl["header"]});
    	if(f["type"]==91||f["type"]==93){
    		 flds.push(Ext.applyIf({name:name+".start","hidden":false},fctrl["editor"]));
    		 flds.push({xtype: 'displayfield',value:"-"});
    		 flds.push(Ext.applyIf({name:name+".end","hidden":false},fctrl["editor"]));
    	}else{
    		flds.push(Ext.applyIf({name:name,"hidden":false},fctrl["editor"]));
    	}
       
    });
    Ext.each(this.getButtons(['doSearch','doReset']),function(btn,i){
        flds.push(btn);
    });
    conf.items=cfs;
    return conf;

};
//dataStore配置
CompositePanel.prototype.defaultDataConfig=function(name) {
	var conf = {};
		conf.root		  = 'itemList';
		conf.totalProperty= 'pageInfo.total';//JsonReader;
		conf.totalRecords = 'pageInfo.total';//XmlReader;
		conf.autoLoad	  = true;
		conf.remoteSort	  = true;
		conf.autoDestroy  = true;
		conf.url		  = this.loadDataUrl;
		conf.paramNames   = {start:'pageInfo.start',limit:'pageInfo.limit',sort:'sortInfo.field',dir:'sortInfo.direct'};
		conf.idProperty	  = this.attrConfig.idProperty;
		conf.listeners	  = {beforeload:function(store,options){
				var recs = store.getModifiedRecords();
				if( recs.length>0 ){
					var cb = window.confirm(recs.length+"条数据已修改但还未提交，当前操作会重新加载数据并导致未提交的修改全部丢失，确定继续？");
					if(cb){
						store.rejectChanges();
					}else{
						return false;
					}
				}
				return true;
			}
		};
	return conf;
};

CompositePanel.prototype.defaultGridConfig=function(region) {
	    var conf = {xtype:'grid'};
	    conf.region=region;
		conf.id='panel-id-'+this.getMetaId();
		conf.title=this.title;
		conf.clicksToEdit='auto';
		conf.selModel=new Ext.grid.CheckboxSelectionModel();
		conf.height=window.screen.availHeight-200;
		conf.autoWidth=true;
		conf.autoScroll=true;
		conf.loadMask={msg:'数据加载中......'};
		conf.bodyCssClass= 'bgWatermarker';
		conf.tbar=this.getButtons(['doCreate','doModify','doDelete','splitter','doReload','doCommit','doFinish']);
	   	conf.items=[];    
	    conf.plugins=['multiSorts'];
	    conf.filter=true;
	return conf;
};

//分页栏配置
CompositePanel.prototype.defaultPageConfig = function(psize){
    var limitCombo = new Ext.form.ComboBox({    
        store:new Ext.data.ArrayStore({
	        fields: [
 	 	            'CODE',
 	 	            'TEXT'
 	 	        ],
 	 	        data: [
 	 	            ["20", '20'],
 	                 ["50", '50'],
 	                ["100", '100']
 	             ]	
 	 	    }),  
        width:50,  editable:false,  
        value:psize?psize:20,
        mode: 'local',    
        triggerAction: 'all',    
        valueField: 'CODE',    
        displayField: 'TEXT'   
    });  
    
      limitCombo.on("select", function(comboBox){ 
    	var pageSize=comboBox.getValue();
    	var limit = parseInt(pageSize); 
     	var pageBar = comboBox.ownerCt;
    	if( pageBar.isXType('paging') ){
    		pageBar.pageSize = limit; 
    		pageBar.cursor=0;
     		pageBar.store.reload({params:{"pageInfo.start":pageBar.cursor,"pageInfo.limit":limit}}); 
     		
    	}else{
    		 
    	}
    });
    
	var conf = {xtype:'paging'};
        conf.pageSize=psize?psize:20;
        conf.displayInfo=true;
        conf.autoWidth=true;
        conf.displayMsg='<font color="red">{0}~{1}</font>条,总数: <font color="red">{2}</font> 条.';
        conf.emptyMsg= "数据记录为空";
        conf.items=['-',limitCombo, '-' ]; 
        conf.combo=limitCombo;
    return conf;
};

CompositePanel.prototype.setPagesize = function(pageSize){
	var limit = parseInt(pageSize); 
	var pageBar = this.gridConfig.bbar;
	if( pageBar.isXType('paging') ){
		alert('paging1');
		pageBar.pageSize = limit;  
		pageBar.store.rejectChanges();
		pageBar.store.reload({params:{"pageInfo.start":pageBar.cursor,"pageInfo.limit":limit}}); 
	}else{
		alert('paging2-no');
		this.refresh({"pageInfo.start":0,"pageInfo.limit":limit});   
	}
};

//导出按钮
CompositePanel.prototype.doExport=function(url){
	if((!url) && (!this.gridConfig.exportUrl) ){return;}
	  Ext.MessageBox.show( {
		title : "请等待",
		msg : "文件下载中",
		progress : true,
		width : 300,
		wait : true,
		waitConfig : {
			interval : 1000
		},
		closable : true
	});

	var iframe = document.createElement("iframe");
	iframe.src = this.pageConfig.exportUrl;
	iframe.style.display = "none";
	document.body.appendChild(iframe);	
	var doc = iframe.contentWindow.document;
	doc.onreadystatechange = function() {
		Ext.MessageBox.hide();
	};
};
